package com.scholarship.system.controller;

import com.scholarship.system.common.dto.Result;
import com.scholarship.system.service.PoliticalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 思政表现评分控制器
 */
@RestController
@RequestMapping("/score/political")
public class PoliticalController {

    private static final Logger logger = LoggerFactory.getLogger(PoliticalController.class);

    @Autowired
    private PoliticalService politicalService;

    /**
     * 获取思政评分列表
     * 
     * @param advisorId 导师ID，为空则获取当前导师下的学生
     * @param keyword   关键字搜索（学号/姓名）
     * @param year      评定年份
     * @param semester  评定学期
     * @return 思政评分列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<List<Map<String, Object>>> getPoliticalScoreList(
            @RequestParam(required = false) Long advisorId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) String semester) {
        try {
            logger.info("获取思政评分列表: advisorId={}, keyword={}, year={}, semester={}",
                    advisorId, keyword, year, semester);

            // 如果没有指定导师ID，则使用当前登录导师的ID
            if (advisorId == null) {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                String username = authentication.getName();
                logger.info("当前登录用户: {}", username);
            }

            return politicalService.getPoliticalScoreList(advisorId, keyword, year, semester);
        } catch (Exception e) {
            logger.error("获取思政评分列表异常", e);
            return Result.error("获取思政评分列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取思政评分详情
     * 
     * @param studentId 学生ID
     * @param year      评定年份
     * @param semester  评定学期
     * @return 思政评分详情
     */
    @GetMapping("/detail")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Map<String, Object>> getPoliticalScoreDetail(
            @RequestParam Long studentId,
            @RequestParam Integer year,
            @RequestParam String semester) {
        try {
            logger.info("获取思政评分详情: studentId={}, year={}, semester={}",
                    studentId, year, semester);
            return politicalService.getPoliticalScoreDetail(studentId, year, semester);
        } catch (Exception e) {
            logger.error("获取思政评分详情异常", e);
            return Result.error("获取思政评分详情失败: " + e.getMessage());
        }
    }

    /**
     * 保存思政评分
     * 
     * @param params 包含评分信息的参数
     * @return 结果
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Void> savePoliticalScore(@RequestBody Map<String, Object> params) {
        try {
            logger.info("保存思政评分: {}", params);
            return politicalService.savePoliticalScore(params);
        } catch (Exception e) {
            logger.error("保存思政评分异常", e);
            return Result.error("保存思政评分失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前学年学期
     * 
     * @return 当前学年学期
     */
    @GetMapping("/current-term")
    @PreAuthorize("hasAuthority('ROLE_TEACHER')")
    public Result<Map<String, Object>> getCurrentTerm() {
        try {
            Map<String, Object> result = new HashMap<>();
            // 默认使用当前年份
            int currentYear = java.time.Year.now().getValue();
            // 根据月份判断学期
            int month = java.time.MonthDay.now().getMonthValue();
            String semester = month >= 2 && month <= 7 ? "春季" : "秋季";

            result.put("year", currentYear);
            result.put("semester", semester);

            return Result.success(result);
        } catch (Exception e) {
            logger.error("获取当前学年学期异常", e);
            return Result.error("获取当前学年学期失败: " + e.getMessage());
        }
    }
}